package com.yc.xunlei;


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;

public class DownLoadTask implements Runnable {
    private int i;//第几个线程
    private long fileSize;//文件总大小
    private long threadSize;//线程数
    private long sizePerThread;//每个线程下载的数据量
    private String url;//url下载地址
    private String downloadPath;//下载后的保存路径
    private static Logger log = Logger.getLogger(DownLoadTask.class.getName());
    private DownLoadedSizeNotify dlsn;

    public DownLoadTask(int i, long fileSize, long threadSize, long sizePerThread, String url, String downloadPath, DownLoadedSizeNotify dlsn) {
        this.i = i;
        this.fileSize = fileSize;
        this.threadSize = threadSize;
        this.sizePerThread = sizePerThread;
        this.url = url;
        this.downloadPath = downloadPath;
        this.dlsn = dlsn;
    }

    @Override
    public void run() {
        //// 1.计算此线程要下载的起始和终止位置
        long start = i * sizePerThread;
        long end = (i + 1) * sizePerThread - 1;
        RandomAccessFile raf = null;
        BufferedInputStream bis = null;
        try {
            //2.让RandomAccessFile的指针偏移到这个位置
            raf = new RandomAccessFile(downloadPath, "rw");
            raf.seek(start);
            // 3.开始下载 Range请求头
            URL u = new URL(url);//最后一个线程要下载的终止位置   Range终点是不包括的
            HttpURLConnection connection = (HttpURLConnection) u.openConnection();
            //设置Range协议头
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Range", "bytes=" + start + "-" + end);  // 请求的范围
            //超时时间
            connection.setConnectTimeout(3000);
            connection.connect(); //用来建立到URL的TCP连接
            //4.获取流
            bis = new BufferedInputStream(connection.getInputStream()); //二进制流
            byte[] bs = new byte[10 * 1024];//每次最多下载10k
            int length = -1;
            while ((length = bis.read(bs, 0, bs.length)) != -1) {
                raf.write(bs, 0, length);
                log.info(Thread.currentThread().getName()+"下载了"+length+"字节");
                if (dlsn != null) {
                   dlsn.notifySize(length);
                }
            }
            log.info( Thread.currentThread().getName()+"下载完毕");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("下载异常" + e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
